import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:vxima/app_book_model.dart';
import 'package:vxima/app_plays_model.dart';
import 'package:vxima/book_playlist_entity.dart';
import 'package:vxima/db_utils.dart';

import 'book_result_entity.dart';

Future<List<AppBookModel>> getBooksResult(int page) async {
  var response = await Dio().get(
      "https://m.ximalaya.com/m-revision/page/category/queryCategoryAlbumsByPage?categoryCode=youshengshu&page=$page&pageSize=30&sort=0&metas=132_2722");
  return new BookResultEntity.fromJson(response.data)
      .data
      .albumBriefDetailInfos
      .map((e) => new AppBookModel.fromModel(e))
      .toList();
}

Future<List<AppPlaysModel>> getPlayList(int id, int page) async {
  print('ddd->$id');
  List<Map> db;
  try {
    db = await getDBPlayDet(id, page);
  } catch (_) {}
  if (null == db || db.length == 0) {
    var response = await Dio().get(
        "http://mobile.ximalaya.com/mobile/others/ca/album/track/$id/true/$page/50");
    var js = response.data;
    var backModel = new BookPlaylistEntity.fromJson(jsonDecode(js));
    await updatePlayList(id, "t_page = ${backModel.tracks.totalCount ~/ 50 + 1} , num = $page");
    await addPlayDet(id, page, backModel.tracks.list);
    List<Map> dbs = await getDBPlayDet(id, page);
    return dbs.map((e) => new AppPlaysModel.fromJson(e)).toList();
  } else {
    return db.map((e) => new AppPlaysModel.fromJson(e)).toList();
  }
}

//https://www.ximalaya.com/revision/search/suggest     {"kw":"he'sh","paidFilter":false,"size":6}
//https://www.ximalaya.com/revision/play/v1/show?id=40764781&num=1&sort=0&size=30&ptype=0
//https://www.ximalaya.com/revision/play/v1/audio?id=54698211&ptype=1
